﻿
using Microsoft.AspNetCore.SignalR;
using WebApi.Hubs;

namespace WebApi.BackgroundWorker;

/// <summary>
/// Represents a background service that performs work in a hosted environment.
/// </summary>
/// <remarks>This class extends <see cref="BackgroundService"/> and provides an implementation for the  <see
/// cref="ExecuteAsync(CancellationToken)"/> method, which contains the logic to be executed  in the background.
/// Override <see cref="ExecuteAsync(CancellationToken)"/> to define the specific  work to be performed.</remarks>
public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IHubContext<ClockHub, IClock> _hubContext;
    /// <summary>
    /// Initializes a new instance of the <see cref="Worker"/> class.
    /// </summary>
    /// <param name="logger">The logger instance used to log messages for the <see cref="Worker"/>.</param>
    /// <param name="hubContext">The SignalR hub context used to communicate with connected clients via the <see cref="ClockHub"/>.</param>
    public Worker(ILogger<Worker> logger, IHubContext<ClockHub, IClock> hubContext)
    {
        _logger = logger;
        _hubContext = hubContext;
    }
    /// <summary>
    /// Executes the background task that periodically sends the current time to all connected clients.
    /// </summary>
    /// <remarks>This method runs in a loop until the <paramref name="stoppingToken"/> is triggered, sending
    /// the current server time to all connected clients every second. The method uses asynchronous delays to avoid
    /// blocking the thread.</remarks>
    /// <param name="stoppingToken">A <see cref="CancellationToken"/> that is triggered when the operation should be canceled.</param>
    /// <returns>A <see cref="Task"/> that represents the asynchronous execution of the background task.</returns>
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // 这里可以执行一些后台任务，比如定时发送当前时间给客户端
            var currentTime = DateTime.Now;
            //_logger.LogInformation("Current time: {time}", currentTime);
            await _hubContext.Clients.All.ShowTime(currentTime);
            //Thread.Sleep(1000); // 每秒钟执行一次
            await Task.Delay(1000, stoppingToken); // 每秒钟执行一次
        }

    }
}
